import BasePlugin from './BasePlugin';

/**
 * 组合插件 - 处理对象组合
 */
export default class GroupPlugin extends BasePlugin {
    constructor() {
        super();
        this.groups = new Map();
        this.groupCounter = 0;
    }

    /**
     * 初始化插件
     */
    init(editor) {
        super.init(editor);
        this._setupEventListeners();
    }

    /**
     * 创建组合
     */
    createGroup() {
        if (!this.isEnabled() || !this.canvas) return;

        const activeObject = this.canvas.getActiveObject();
        if (!activeObject || activeObject.type !== 'activeSelection') return;

        const group = activeObject.toGroup();
        const groupId = `group_${++this.groupCounter}`;
        group.set('id', groupId);
        group.set('name', `Group ${this.groupCounter}`);

        // 保存组合信息
        this.groups.set(groupId, {
            id: groupId,
            name: group.name,
            objects: group.getObjects()
        });

        this.canvas.setActiveObject(group);
        this.canvas.renderAll();

        this._emitGroupEvent('create', group);
        return group;
    }

    /**
     * 解散组合
     */
    ungroup() {
        if (!this.isEnabled() || !this.canvas) return;

        const activeObject = this.canvas.getActiveObject();
        if (!activeObject || activeObject.type !== 'group') return;

        const groupId = activeObject.id;
        const objects = activeObject.toActiveSelection();

        // 移除组合信息
        this.groups.delete(groupId);

        this.canvas.setActiveObject(objects);
        this.canvas.renderAll();

        this._emitGroupEvent('ungroup', objects);
        return objects;
    }

    /**
     * 添加对象到组合
     */
    addToGroup(group, objects) {
        if (!this.isEnabled() || !this.canvas || !group || !objects) return;

        if (!Array.isArray(objects)) {
            objects = [objects];
        }

        objects.forEach(obj => {
            group.addWithUpdate(obj);
        });

        // 更新组合信息
        const groupInfo = this.groups.get(group.id);
        if (groupInfo) {
            groupInfo.objects = group.getObjects();
        }

        this.canvas.renderAll();
        this._emitGroupEvent('add', group, objects);
    }

    /**
     * 从组合中移除对象
     */
    removeFromGroup(group, objects) {
        if (!this.isEnabled() || !this.canvas || !group || !objects) return;

        if (!Array.isArray(objects)) {
            objects = [objects];
        }

        objects.forEach(obj => {
            group.removeWithUpdate(obj);
        });

        // 更新组合信息
        const groupInfo = this.groups.get(group.id);
        if (groupInfo) {
            groupInfo.objects = group.getObjects();
        }

        this.canvas.renderAll();
        this._emitGroupEvent('remove', group, objects);
    }

    /**
     * 获取所有组合
     */
    getGroups() {
        return Array.from(this.groups.values());
    }

    /**
     * 获取组合信息
     */
    getGroupInfo(groupId) {
        return this.groups.get(groupId);
    }

    /**
     * 设置组合名称
     */
    setGroupName(group, name) {
        if (!this.isEnabled() || !this.canvas || !group) return;

        group.set('name', name);

        // 更新组合信息
        const groupInfo = this.groups.get(group.id);
        if (groupInfo) {
            groupInfo.name = name;
        }

        this.canvas.renderAll();
        this._emitGroupEvent('rename', group);
    }

    /**
     * 锁定组合
     */
    lockGroup(group) {
        if (!this.isEnabled() || !this.canvas || !group) return;

        group.set({
            lockMovementX: true,
            lockMovementY: true,
            lockRotation: true,
            lockScalingX: true,
            lockScalingY: true,
            hasControls: false,
            selectable: false
        });

        group.getObjects().forEach(obj => {
            obj.set({
                lockMovementX: true,
                lockMovementY: true,
                lockRotation: true,
                lockScalingX: true,
                lockScalingY: true,
                hasControls: false,
                selectable: false
            });
        });

        this.canvas.renderAll();
        this._emitGroupEvent('lock', group);
    }

    /**
     * 解锁组合
     */
    unlockGroup(group) {
        if (!this.isEnabled() || !this.canvas || !group) return;

        group.set({
            lockMovementX: false,
            lockMovementY: false,
            lockRotation: false,
            lockScalingX: false,
            lockScalingY: false,
            hasControls: true,
            selectable: true
        });

        group.getObjects().forEach(obj => {
            obj.set({
                lockMovementX: false,
                lockMovementY: false,
                lockRotation: false,
                lockScalingX: false,
                lockScalingY: false,
                hasControls: true,
                selectable: true
            });
        });

        this.canvas.renderAll();
        this._emitGroupEvent('unlock', group);
    }

    /**
     * 发送组合事件
     */
    _emitGroupEvent(type, group, objects = []) {
        this.editor.emit('group:applied', {
            type,
            group: group.id ? this.getGroupInfo(group.id) : null,
            objects
        });
    }

    /**
     * 设置事件监听
     */
    _setupEventListeners() {
        if (!this.canvas) return;

        // 监听对象选择事件
        this.canvas.on('selection:created', (e) => {
            if (!this.isEnabled()) return;

            const activeObject = e.target;
            if (activeObject.type === 'activeSelection') {
                // 可以组合
                this.editor.emit('group:selectable', true);
            }
        });

        this.canvas.on('selection:updated', (e) => {
            if (!this.isEnabled()) return;

            const activeObject = e.target;
            if (activeObject.type === 'activeSelection') {
                // 可以组合
                this.editor.emit('group:selectable', true);
            } else if (activeObject.type === 'group') {
                // 可以解散
                this.editor.emit('group:selected', this.getGroupInfo(activeObject.id));
            }
        });

        this.canvas.on('selection:cleared', () => {
            if (!this.isEnabled()) return;
            this.editor.emit('group:selectable', false);
        });

        // 监听对象修改事件
        this.canvas.on('object:modified', (e) => {
            if (!this.isEnabled()) return;

            const target = e.target;
            if (target.type === 'group') {
                // 更新组合信息
                const groupInfo = this.groups.get(target.id);
                if (groupInfo) {
                    groupInfo.objects = target.getObjects();
                }
            }
        });
    }

    /**
     * 销毁插件
     */
    destroy() {
        if (this.canvas) {
            // 解散所有组合
            this.groups.forEach((groupInfo) => {
                const objects = this.canvas.getObjects();
                const group = objects.find(obj => obj.id === groupInfo.id);
                if (group) {
                    group.toActiveSelection();
                }
            });
            this.groups.clear();
        }
        super.destroy();
    }
} 